package di

import (
	"database/sql"
	"fmt"
	_ "github.com/denisenkom/go-mssqldb"
	"github.com/mix-go/xdi"
	"github.com/yupeng2015/xsql"
	"hy_808/configor"
)

func InitMssql() (*xsql.DB, error) {
	//oracle://root:123456@127.0.0.1:1521/orcl
	c := configor.ConfigGlobal.Database.Mssql
	connStr := fmt.Sprintf("server=%s;user id=%s;password=%s;port=%d;database=%s;encrypt=disable", c.Host, c.User, c.Password, c.Port, c.Database)
	db, err := sql.Open("sqlserver", connStr)
	if err != nil {
		panic("mssql,sql.Open异常" + err.Error())
	}
	if err = db.Ping(); err != nil {
		panic("mssql,db.Ping异常" + err.Error())
	}

	xdb := xsql.New(db, xsql.Options{
		ColumnQuotes: " ",
		Placeholder:  "@",
		DebugFunc: func(l *xsql.Log) {
			//log.Println(l.SQL)
		}})

	//注入到依赖
	obj := xdi.Object{
		Name: "mssql_dst",
		New: func() (interface{}, error) {
			return xdb, nil
		},
	}
	if err = xdi.Provide(&obj); err != nil {
		panic(err)
	}

	return xdb, nil
}
